package com.android.djlmapp.activity.order;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.base.BaseWebActivity;
import com.android.djlmapp.activity.home.web.base.BaseWebChromeClient;
import com.android.djlmapp.activity.kaika.QianMingActivity;
import com.android.djlmapp.activity.kaika.SelectNumChildActivity;
import com.android.djlmapp.activity.kaika.TiaoXingCodeScanerActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.dialog.ChoosImgDialog;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.js_interface.BaseJsInterface;
import com.android.djlmapp.js_interface.order.AbOrderDetailJsInterfaceCallBack;
import com.android.djlmapp.js_interface.order.OrderDetailJsInterface;
import com.android.djlmapp.listener.read.GetPhotoUrlListener;
import com.android.djlmapp.listener.read.SubReadDataListener;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.kaika.SubReadCardDataUtils;
import com.android.djlmapp.tools.other.TextUtil;
import com.android.djlmapp.tools.read.WriteCardUtils;
import com.android.readcard.activity.WriteCardActivity;
import com.android.readcard.bean.BackReadInfo;
import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.bean.ReadIccidAndWriteCardInfo;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.google.gson.Gson;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import static com.android.djlmapp.activity.kaika.QianMingActivity.UPLOAD_IMG_SUCCESS_RESULT_DATA;
import static com.android.djlmapp.js_interface.BaseJsInterface.CALL_METHEOD_NAME;
import static com.android.djlmapp.js_interface.BaseJsInterface.CALL_METHEOD_UP_IMG_NAME;
import static com.android.djlmapp.js_interface.BaseJsInterface.MORE_FUN_JS_SIGN_KEY;

/**
 * @Author wangziheng
 * @ProjectName djlm
 * @ClassName OrderDetailActivity
 * @package com.android.djlmapp.activity.order
 * @data 2018/12/25 17:12
 * @Describe 订单详情
 * @Change
 */
public class OrderDetailActivity extends BaseWebActivity {
    /**
     * 订单号
     */
    public static final String ORDER_DETAIL_ORDER_SN_KEY = "ORDER_DETAIL_ORDER_SN_KEY";
    /**
     * 选择照片的弹窗
     * 相机拍摄
     * 相册选择
     */
    private ChoosImgDialog choosImgDialog;

    public static final int QIANMING_INTENT_REQUEST_CODE = 1;
    public static final int SELECT_TEL_NUM_REQUEST_CODE = 2;
    public static final int SELECT_SIM_NUM_REQUEST_CODE = 3;
    private String mOrderNum;

    @Override
    protected void initView() {
        setWebChromeClient(mDefaultWebChromeClient); // 设置标题
        super.initView();
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        mSwipeRefreshLayout.setEnabled(true);
        mSwipeRefreshLayout.setOnRefreshListener(this::loadPage);
    }

    private WebChromeClient mDefaultWebChromeClient = new BaseWebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            mTitleTv.setText("订单详情");
        }
    };

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventReadCardCode.A:
                // 读卡
                BackReadInfo data = (BackReadInfo) event.getData();
                ReadCardInfo readInfo = data.getInfo();
                CardData cardData = data.getCardData();
                String chuanma = data.getChuanma();
                Log.i("读卡结果", "------ReadCardInfo------" + readInfo.toString());
                Log.i("读卡结果", "------CardData------" + cardData.toString());
                Log.i("读卡结果", "------chuanma------" + chuanma);

                // 上传身份信息获取经办人数据
                SubReadCardDataUtils.getJingBanRenData(readInfo, cardData, chuanma, new SubReadDataListener() {
                    @Override
                    public void subPhotoSuc(String needJb, String photoUrl) {
                        Gson gson = new Gson();
                        String strJson = gson.toJson(cardData);
                        Log.i("上传身份证", "subPhotoSuc: " + strJson);
                        mAgentWeb.getJsAccessEntrace().quickCallJs("returnCARD", strJson);
                    }

                    @Override
                    public void subErr(String msg) {
                        ToastUtils.showShortToast(OrderDetailActivity.this, msg);
                    }
                });
                break;
            case EventCodes.EventReadCardCode.B: // 返回iccid
                String mUrl = "";
                ReadIccidAndWriteCardInfo iccidData = (ReadIccidAndWriteCardInfo) event.getData();
                Log.e("项目异常写卡", event.getCode() + "------ReadIccidAndWriteCardInfo--返回iccid----" + iccidData.toString());
                String iccidNum = iccidData.getIccidNum();
                int writeType = iccidData.getWriteType();
                String errMsg = iccidData.getErrMsg(); // 错误信息
                String imsi = iccidData.getImsi(); // imsi
                switch (writeType) {
                    case 0: // 废卡重置
                        WriteCardUtils.clearCard(iccidNum, imsi, new GetPhotoUrlListener() {
                            @Override
                            public void backPhotoUrl(int backType, String result) {
                                // eventbus通知WriteCardActivity,废卡重置完成了,成功失败都要提示并且关闭写卡界面
                                Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
                                EventBusUtil.sendEvent(clearCardEvent);
                                WriteCardUtils.showMsg(OrderDetailActivity.this, "废卡重置结果", result);
                            }
                        });
                        break;
                    case 1: // 写卡
                        mUrl = GlobalUrls.BAI_KA;
                        // 上传iccid获取短信中心号和imsi并eventbus返回给WriteCardActivity
                        WriteCardUtils.startWrite(OrderDetailActivity.this, mUrl, iccidNum, mOrderNum, "写卡");
                        break;
                    case 2: // 补卡
                        mUrl = GlobalUrls.BU_KA;
                        // 上传iccid获取短信中心号和imsi并eventbus返回给WriteCardActivity
                        WriteCardUtils.startWrite(OrderDetailActivity.this, mUrl, iccidNum, mOrderNum, "补卡");
                        break;
                    default:
                        break;
                }
                break;
            case EventCodes.EventReadCardCode.D: // 返回写卡结果
                String sucUrl = "";
                ReadIccidAndWriteCardInfo xiekaData = (ReadIccidAndWriteCardInfo) event.getData();
                Log.e("项目异常写卡", event.getCode() + "------ReadIccidAndWriteCardInfo-返回写卡结果-----" + xiekaData.toString());
                String iccidNum1 = xiekaData.getIccidNum();
                int writeType1 = xiekaData.getWriteType();
                String errMsg1 = xiekaData.getErrMsg(); // 错误信息
                String imsi1 = xiekaData.getImsi(); // imsi
                // 判断errMsg是不是空,是空值就是写卡成功
                if (TextUtils.isEmpty(errMsg1)) {

                    switch (writeType1) {
                        case 1:
                            sucUrl = GlobalUrls.BAI_KA_OK;
                            WriteCardUtils.writeSucSubmit(OrderDetailActivity.this, sucUrl, iccidNum1, mOrderNum, "写卡", new GetPhotoUrlListener() {
                                @Override
                                public void backPhotoUrl(int backType, String photoUrl) {
                                    Log.e("项目异常backType", "------backType------" + backType);
                                    if (backType == 1) {
                                        mAgentWeb.getUrlLoader().reload();
                                    }
                                }
                            });
                            break;
                        case 2:
                            sucUrl = GlobalUrls.BU_KA_OK;
                            WriteCardUtils.writeSucSubmit(OrderDetailActivity.this, sucUrl, iccidNum1, mOrderNum, "补卡", null);

                            break;
                        default:
                            break;
                    }

                } else {
                    // 写卡失败,提示错误
                    Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
                    EventBusUtil.sendEvent(clearCardEvent);
                    switch (writeType1) {
                        case 1:
                            WriteCardUtils.showMsg(OrderDetailActivity.this, "写卡结果", errMsg1);
                            break;
                        case 2:
                            WriteCardUtils.showMsg(OrderDetailActivity.this, "补卡结果", errMsg1);
                            break;
                        default:
                            break;
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取js交互的key
     *
     * @return
     */
    @Override
    public String getJsInterfaceKey() {
        return MORE_FUN_JS_SIGN_KEY;
    }

    /**
     * 设置js交互监听
     *
     * @return
     */
    @Override
    public BaseJsInterface getJsInterface() {
        return new OrderDetailJsInterface(this, mOrderDetailJsInterfaceCallBack, mAgentWeb);
    }

    private AbOrderDetailJsInterfaceCallBack mOrderDetailJsInterfaceCallBack = new AbOrderDetailJsInterfaceCallBack() {
        @Override
        public void getImg() {
            if (choosImgDialog == null) {
                choosImgDialog = new ChoosImgDialog(OrderDetailActivity.this);
                choosImgDialog.setItemClickListener(v -> {
                    choosImgDialog.cancel();
                    switch (v.getId()) {
                        case R.id.dialog_Title_tv:
                            takePhoto();
                            break;
                        case R.id.dialog_Content_tv:
                            choosePhoto();
                            break;
                        default:
                            break;
                    }
                });
            }
            choosImgDialog.showDialog();
        }

        @Override
        public void getSign() {
            Intent intent = new Intent(OrderDetailActivity.this, QianMingActivity.class);
            startActivityForResult(intent, QIANMING_INTENT_REQUEST_CODE);
        }

        @Override
        public void getPhonenum(String json) {
            // NativeRetuion
            Intent intent = new Intent(OrderDetailActivity.this, SelectNumChildActivity.class);
            intent.putExtra(SelectNumChildActivity.REQUEST_PARAMS_KEY, json);
            startActivityForResult(intent, SELECT_TEL_NUM_REQUEST_CODE);
        }

        @Override
        public void getSimNum() {
            Intent intent = new Intent(OrderDetailActivity.this, TiaoXingCodeScanerActivity.class);
            startActivityForResult(intent, SELECT_SIM_NUM_REQUEST_CODE);
        }

        @Override
        public void bkSubmit(String json) {
            try {
                JSONObject jsonObject = new JSONObject(json);
                String type = jsonObject.optString("type");
                if ("7".equals(type)) {
                    // 开始补卡
                    mOrderNum = jsonObject.optString("order_sn");

                    // 蓝牙对话框
                    startActivity(new Intent(OrderDetailActivity.this, WriteCardActivity.class).putExtra("WriteType", 1));
                }
            } catch (JSONException e) {
                ToastUtils.showShortToast(OrderDetailActivity.this, "数据解析异常");
                e.printStackTrace();
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case QIANMING_INTENT_REQUEST_CODE:
                    // 签名照
                    if (resultCode == 2) {
                        String imgUrl = data.getStringExtra(UPLOAD_IMG_SUCCESS_RESULT_DATA);
                        mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_UP_IMG_NAME, imgUrl);
                    }
                    break;
                case SELECT_TEL_NUM_REQUEST_CODE:
                    // 选择号码
                    if (resultCode == RESULT_OK) {
                        String selectNum = data.getStringExtra(SelectNumChildActivity.SELECTED_TEL_KEY);
                        mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_NAME, selectNum);
                    }
                    break;
                case SELECT_SIM_NUM_REQUEST_CODE:
                    // 扫描sim卡号
                    if (resultCode == 0) {
                        Bundle str = data.getExtras();
                        String result = str.getString(CodeUtils.RESULT_STRING);
                        int resultType = str.getInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                        if (resultType == CodeUtils.RESULT_SUCCESS) {
                            if (result == null) {
                                ToastUtils.showShortToast(OrderDetailActivity.this, "扫描失败，沒有扫描到卡体，请重试");
                                return;
                            }
                            if (result.length() >= 19) {
                                String keyvalue = result.substring(0, 19);
                                if (TextUtil.isNumeric(keyvalue)) {
                                    // 是纯数字
                                    mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_NAME, keyvalue);
                                } else {
                                    ToastUtils.showShortToast(OrderDetailActivity.this, "请确定您扫描的是SIM卡");
                                }
                            } else {
                                ToastUtils.showShortToast(OrderDetailActivity.this, "请确定您扫描的是SIM卡");
                            }
                        } else {
                            ToastUtils.showShortToast(OrderDetailActivity.this, "扫描失败，请重新扫描");
                        }
                    }
                    break;
            }
        }
    }


    @Override
    public void takeSuccess(TResult result) {
        ArrayList<TImage> images = result.getImages();
        String compressPath = images.get(0).getCompressPath();
        if (compressPath != null && !TextUtils.isEmpty(compressPath)) {
            File file = new File(compressPath);
            MyApplication.getInstance().getHttpTools().upLoadImg(file, new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_UP_IMG_NAME, response.body());
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    showToast(getString(R.string.connect_sever_error_msg));
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    if (choosImgDialog != null) {
                        choosImgDialog.cancel();
                    }
                }
            });
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        runOnUiThread(() -> {
            showToast("图片上传失败,请重新选择图片上传");
            if (choosImgDialog != null) {
                choosImgDialog.cancel();
            }
        });
    }
}
